package com.sky.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user/addressBook")
@Api(tags = "C端地址簿接口")
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;
    /**
     * 新增地址
     * @param addressBook
     * @return
     */
    /**
     * 查询当前登录用户的所有地址信息
     *
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("查询当前登录用户的所有地址信息")
    public Result<List<AddressBook>> list() {
        //获取当前登录用户id
        Long userId = BaseContext.getCurrentId();
        System.out.println("当前登录用户ID：" + userId);
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId, userId);
        return Result.success(addressBookService.list(queryWrapper));

    }
    /**
     * 新增地址
     *
     * @param addressBook
     * @return
     */
    @PostMapping
    @ApiOperation("新增地址")
    public Result save(@RequestBody AddressBook addressBook) {
        Long userId = BaseContext.getCurrentId();
        System.out.println("当前登录用户ID：" + userId);
        addressBook.setUserId(userId);
        return addressBookService.save(addressBook) ? Result.success() : Result.error("新增地址失败");
    }
    /**
     * 根据id修改地址
     *
     * @param addressBook
     * @return
     */
    @PutMapping
    @ApiOperation("根据id修改地址")
    public Result update(@RequestBody AddressBook addressBook) {
        // 1. 获取当前登录用户ID（用于权限校验）
        Long userId = BaseContext.getCurrentId();
        System.out.println("当前登录用户ID：" + userId);
        // 2. 查询旧地址信息（验证地址是否属于当前用户）
        AddressBook oldAddress = addressBookService.getById(addressBook.getId());
        if (oldAddress == null) {
            return Result.error("地址不存在");
        }
        // 校验：确保当前用户只能修改自己的地址
        if (!oldAddress.getUserId().equals(userId)) {
            return Result.error("无权修改他人地址");
        }

        // 3. 直接更新（无需删除再插入）
        addressBook.setUserId(userId); // 确保用户ID不变（防止恶意修改）
        boolean success = addressBookService.updateById(addressBook);
        return success ? Result.success() : Result.error("修改地址失败");
    }

    /**
     * 根据id查询地址
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation("根据id查询地址")
    public Result<AddressBook> get(@PathVariable Long id) {
        return Result.success(addressBookService.getById(id));
    }
    /**
     * 根据id删除地址
     *
     * @param id
     * @return
     */
    @DeleteMapping
    @ApiOperation("根据id删除地址")
    public Result delete(@RequestParam Long id) {
        return addressBookService.removeById(id) ? Result.success() : Result.error("删除地址失败");
    }
    /**
     * 设置默认地址
     *
     * @param addressBook
     * @return
     */
    @PutMapping("/default")
    @ApiOperation("设置默认地址")
    public Result setDefault(@RequestBody AddressBook addressBook){
        return addressBookService.setDefault(addressBook) ? Result.success() : Result.error("设置默认地址失败");
    }
    /**
     * 查询默认地址
     *
     **/
    @GetMapping("/default")
    @ApiOperation("查询默认地址")
    public Result<AddressBook> getDefault() {
        //获取当前登录用户id
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId, userId);
        queryWrapper.eq(AddressBook::getIsDefault, 1);
        AddressBook one = addressBookService.getOne(queryWrapper);
        if (one == null) {
            return Result.error("没有查询到默认地址");
        }
        return Result.success(one);
    }

}